
<template>
  <div style="background: #EEEEEE7F; min-height: 100vh">
    <van-nav-bar
        title="仪器申请"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />


    <van-space direction="vertical" fill>
      <div style="height: 8px;"></div>
      <InstrumentCard :instrument="instrumentRef"/>

      <van-cell-group inset>
        <van-cell title="仪器当前位置" :label="instrumentRoom" />
        <van-cell title="仪器借用位置" is-link value="选择房间" :label="selectRoomTextRef" @click="showRoomSelector = true"/>
      </van-cell-group>

      <van-cell-group inset>
        <van-cell style="--van-cell-horizontal-padding: 8px">
          <van-field v-model="selectReviewerTextRef" is-link label="审核人" placeholder="选择审核人" readonly @click="showPicker = true"/>
        </van-cell>
        <!--审核人选择-->
        <van-popup v-model:show="showPicker" destroy-on-close position="bottom" round>
          <van-picker
              :columns="reviewerRef"
              @cancel="showPicker = false"
              @confirm="onConfirm"
          />
        </van-popup>
      </van-cell-group>

      <van-cell-group inset>
        <van-field
            v-model="message"
            rows="2"
            autosize
            label="备注"
            type="textarea"
            maxlength="50"
            placeholder="请输入备注"
            show-word-limit
        />
      </van-cell-group>

      <van-cell-group inset>
        <van-cell label="" title="本次扣除积分" :value=deductPoints style="--van-cell-value-color: #46afff"/>
        <van-cell label="" title="剩余积分" :value=userPoints />
      </van-cell-group>


      <div style="width: auto; margin: 0 16px 8px 16px">
        <van-button round type="primary" style="width: 100%;" @click="reservation">立即申请</van-button>
      </div>
    </van-space>

  </div>
  <van-dialog v-model:show="showRoomSelector" show-cancel-button width="100%">
    <RoomSelector @selectRoom="onRoomSelected" select-room-type="LAB"/>
  </van-dialog>
</template>


<script setup lang="ts">
import { ref } from "vue";

import { borrowInstrumentFromList} from "@/apps/client/utils/instrumentApi.js";
import { closeToast, showNotify, showToast, showLoadingToast } from "vant";
import { getUserInfo } from "@/apps/client/utils/userApi.js";
import RoomSelector from "@/apps/client/components/RoomSelector.vue";

const router = useRouter()
const onClickLeft = () => {
  router.back();
};

const instrumentRef = ref({});
const instrumentId = sessionStorage.getItem("selectInstrumentId");

// UI字段
const reviewerRef = ref([]);
const selectReviewerTextRef = ref(null);
let selectReviewer = null;

const message = ref('');
const userPoints = ref(null);
const deductPoints = ref(null);
const instrumentRoom = ref(null);
// 初始化仪器信息和审核人
import { getInstrumentInfo } from "@/apps/client/utils/instrumentApi.js";
import {useRouter} from "vue-router";
import InstrumentCard from "@/apps/client/components/instrumentCard.vue";
getInstrumentInfo(instrumentId).then((body) => {
  let instrument: object = body.data.instrument;
  instrumentRef.value = instrument;

  reviewerRef.value = body.data.reviewer.map(item => ({
    text: item.name,
    value: item.id
  }));

  instrumentRoom.value = instrument["room"]["subType"] + ' ' + instrument["room"]["number"]

  const points = Number(sessionStorage.getItem("points"));
  userPoints.value = `${points - instrument['pointsCost']}积分`;
  deductPoints.value = instrument['pointsCost'] + "积分";
});

const showPicker = ref(false);
const onConfirm = ({ selectedValues, selectedOptions }) => {
  showPicker.value = false;
  selectReviewerTextRef.value = selectedOptions[0].text;
  selectReviewer = selectedOptions[0];
};

// 房间选择
const showRoomSelector = ref(false);
const selectRoomRef = ref(null);
const selectRoomTextRef = ref(null);

function onRoomSelected(room) {
  selectRoomRef.value = room;
  selectRoomTextRef.value = `${room.subType} ${room.number}`;
  showRoomSelector.value = false;
}

// 提交借用申请
function reservation() {
  if (!selectReviewer) {
    showNotify({ message: '请选择审核人' });
    return;
  }

  if (!selectRoomRef.value) {
    showNotify({ message: '请选择归还房间' });
    return;
  }

  openLoadingDialog();

  const payload = {
    instrumentId: Number(instrumentId),
    reviewerId: selectReviewer.value,
    remark: message.value,
    returnRoomId: selectRoomRef.value.id,
  };

  borrowInstrumentFromList(payload)
      .then(body => {
        if (body.code === 200) {
          showNotify({ type: "success", message: "借用申请成功" });
          onRefresh();
        } else {
          showNotify({ message: body.msg || "借用申请失败" });
        }
      })
      .catch(err => {
        showToast(err.message || '借用失败，请稍后重试');
      })
      .finally(() => {
        closeToast();
      });
}

const openLoadingDialog = () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  });
};

const loading = ref(false);
async function onRefresh() {
  loading.value = true;
  await getUserInfo().then((body) => {
    let data = body.data;
    sessionStorage.setItem("points", data.points);
    userPoints.value = `${data.points}积分`;
  });
  loading.value = false;
}
</script>


<style scoped>

</style>